package com.client.server;

import com.client.handler.ClientHandler;
import com.common.code.msgpack.MsgPackDecode;
import com.common.code.msgpack.MsgPackEncode;
import com.common.constant.CommonConstant;
import com.common.message.vo.BaseMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientServer {

    private final static Logger logger = LoggerFactory.getLogger(ClientServer.class);

    private NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
    private Channel channel;
    private Bootstrap bootstrap;
    private ChannelFuture future;

    public static void main(String[] args) {
        ClientServer clientServer = new ClientServer();
        clientServer.start();
//        clientServer.sendMessage();
    }

    public void start(){
        try {
            bootstrap = new Bootstrap();
            bootstrap
                    .group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline p = socketChannel.pipeline();
//                            p.addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, -4, 0));
                            p.addLast(new MsgPackDecode());
                            p.addLast(new MsgPackEncode());
                            p.addLast(new ClientHandler());
                        }
                    });
            future = bootstrap.connect(CommonConstant.DEFAULT_TCP_HOST, CommonConstant.DEFAULT_TCP_PORT);
            channel = future.channel();
            future.addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture futureListener) throws Exception {
                    if (futureListener.isSuccess()) {
//                        channel = futureListener.channel();
                        logger.info("Connect to server successfully!{}", channel.remoteAddress());
                        sendMessage();

                    }
                }
            });

        } catch (Exception e) {
            logger.error("[ERROR-CLIENTSERVER]:{}", e);
            try {
                future.channel().closeFuture().sync();
                workGroup.shutdownGracefully().sync();
            } catch (InterruptedException e1) {
                logger.error("[ERROR-CLIENTSERVER]:{}", e1);
            }

        }
    }

    public void sendMessage() {
        logger.info("client ready send Message!");
        BaseMessage baseMessage = new BaseMessage();
        baseMessage.setContent("$,GWA100171001,31,aaaaa,bbbbbb,cccccc,dddd");
        if (channel != null && channel.isActive()) {
            logger.info("client send Message!");
            channel.writeAndFlush(baseMessage);
            logger.info("client send Message finish!");
        }else{
            logger.info("channel is inactive!");
        }
    }
}
